package com.lh.glassmuseum.service;

import javafx.application.Platform;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;

public class InputService {
    public static TextField input = new TextField();;
    public static void constructInput(AnchorPane root){
        //验票输入内容
        AnchorPane.setTopAnchor(input,300.0);
        AnchorPane.setLeftAnchor(input, 430.0);
        AnchorPane.setRightAnchor(input, 55.0);
        input.requestFocus();
        input.setOnKeyPressed(InputService::handleEnter);
        //输入框焦点保护层
        input.focusedProperty().addListener((obs, oldVal, newVal) -> {
            if (!newVal) Platform.runLater(input::requestFocus);
        });
        root.getChildren().add(input);
    }

    /**
     * 处理输入内容
     * @param event 按键事件
     */
    public static void handleEnter(KeyEvent event) {
        if (event.getCode() == KeyCode.ENTER) {
//            TextField textField = ((TextField)event.getSource());
            String cmd = input.getText();
            handleEnterAction(cmd);
//            input.clear();
        }
    }

    // 处理回车事件的业务逻辑
    public static void handleEnterAction(String inputText) {
        // 根据输入内容显示不同信息
        if (inputText.isEmpty()) {
            TipService.updateDisplay("⚠️ 输入内容不能为空！");
        } else {
            TipService.updateDisplay("已接收内容:\n" + inputText+",正在验票...");
            //发送请求
            HttpService.sendHttpRequest(inputText);
        }
    }
}
